import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { Form, Input, Button, Checkbox, Typography, message, theme } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import '@ant-design/cssinjs';
import { useAuth } from '../authProvider';
// 直接导入图片（确保yy.webp与Login.tsx在同一目录）
import doctorImage from './yy.webp';

const { Title, Text } = Typography;
const { useToken } = theme;

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [cardHovered, setCardHovered] = useState(false);
  const [usernameFocused, setUsernameFocused] = useState(false);
  const [passwordFocused, setPasswordFocused] = useState(false);
  const [checkboxHovered, setCheckboxHovered] = useState(false);
  const [buttonHovered, setButtonHovered] = useState(false);
  const [linkHovered, setLinkHovered] = useState(false);
  
  const { token } = useToken();
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  const from = (location.state as { from: { pathname: string } })?.from?.pathname || '/';
  
  const handleSubmit = async (values: { username: string; password: string; remember: boolean }) => {
    setLoading(true);
    try {
      const success = await login(values.username, values.password);
      if (success) {
        message.success('登录成功');
        navigate(from, { replace: true });
      } else {
        message.error('用户名或密码错误，请重试');
      }
    } catch (err) {
      message.error('登录过程中发生错误，请稍后重试');
      console.error('Login error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      document.body.classList.add('loaded');
    }, 300);
    return () => clearTimeout(timer);
  }, []);

  return (
    <div 
      style={{
        // 使用导入的图片变量作为背景
        backgroundImage: `url(${doctorImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'left center', // 左侧图片主体居中
        backgroundRepeat: 'no-repeat',
        backgroundAttachment: 'fixed',
        position: 'relative',
        minHeight: '100vh',
        display: 'flex',
        justifyContent: 'flex-end', // 登录卡片靠右
        alignItems: 'center',
        paddingRight: '8%', // 右侧间距
        filter: 'saturate(1.05) brightness(0.98)',
        transition: 'all 0.6s cubic-bezier(0.23, 1, 0.32, 1)'
      }}
    >
      {/* 渐变遮罩层 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, rgba(15, 82, 186, 0.15) 0%, rgba(255, 255, 255, 0.7) 100%)',
        zIndex: 1
      }}></div>
      
      {/* 登录卡片 - 带悬浮动效 */}
      <div 
        style={{
          width: 420,
          padding: 48,
          borderRadius: token.borderRadiusLG + 4,
          boxShadow: cardHovered 
            ? '0 20px 40px rgba(0, 0, 0, 0.12), 0 8px 16px rgba(15, 82, 186, 0.08)'
            : '0 10px 25px rgba(0, 0, 0, 0.08), 0 4px 8px rgba(15, 82, 186, 0.05)',
          position: 'relative',
          zIndex: 2,
          backgroundColor: 'rgba(255, 255, 255, 0.96)',
          backdropFilter: 'blur(8px)',
          transition: 'all 0.4s cubic-bezier(0.23, 1, 0.32, 1)',
          transform: cardHovered ? 'translateY(-6px)' : 'translateY(0)'
        }}
        onMouseEnter={() => setCardHovered(true)}
        onMouseLeave={() => setCardHovered(false)}
      >
        {/* 系统标题区域 */}
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <div style={{
            width: 72,
            height: 72,
            margin: '0 auto 20px',
            borderRadius: '50%',
            background: 'linear-gradient(135deg, #0f52ba 0%, #1e88e5 100%)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: '0 4px 12px rgba(15, 82, 186, 0.25)'
          }}>
            <UserOutlined style={{ fontSize: 36, color: '#fff' }} />
          </div>
          <Title level={2} style={{ 
            margin: 0,
            color: '#0a3d77',
            fontWeight: 600,
            letterSpacing: 0.5
          }}>
            智慧医院管理系统
          </Title>
          <Text style={{ color: '#6b7280', marginTop: 8, display: 'inline-block' }}>
            专业 · 高效 · 安全
          </Text>
        </div>

        <Form
          name="login"
          initialValues={{ username: 'admin', password: '123', remember: true }}
          onFinish={handleSubmit}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          {/* 用户名输入框 */}
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
            style={{ marginBottom: 20 }}
          >
            <Input
              prefix={<UserOutlined style={{ color: '#0f52ba80' }} />}
              placeholder="用户名"
              size="large"
              style={{
                height: 52,
                borderRadius: token.borderRadius,
                borderColor: usernameFocused ? '#1e88e5' : '#e2e8f0',
                boxShadow: usernameFocused ? '0 0 0 3px rgba(30, 136, 229, 0.1)' : 'none',
                transition: 'all 0.3s ease'
              }}
              onFocus={() => setUsernameFocused(true)}
              onBlur={() => setUsernameFocused(false)}
            />
          </Form.Item>

          {/* 密码输入框 */}
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
            style={{ marginBottom: 24 }}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: '#0f52ba80' }} />}
              placeholder="密码"
              size="large"
              style={{
                height: 52,
                borderRadius: token.borderRadius,
                borderColor: passwordFocused ? '#1e88e5' : '#e2e8f0',
                boxShadow: passwordFocused ? '0 0 0 3px rgba(30, 136, 229, 0.1)' : 'none',
                transition: 'all 0.3s ease'
              }}
              onFocus={() => setPasswordFocused(true)}
              onBlur={() => setPasswordFocused(false)}
            />
          </Form.Item>

          {/* 记住我选项 */}
          <Form.Item 
            name="remember" 
            valuePropName="checked"
            style={{ marginBottom: 28 }}
          >
            <Checkbox 
              style={{ 
                color: checkboxHovered ? '#0f52ba' : '#4b5563',
                transition: 'color 0.3s ease'
              }}
              onMouseEnter={() => setCheckboxHovered(true)}
              onMouseLeave={() => setCheckboxHovered(false)}
            >
              记住我
            </Checkbox>
          </Form.Item>

          {/* 登录按钮 */}
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
              style={{
                height: 54,
                fontSize: 16,
                fontWeight: 500,
                borderRadius: token.borderRadius,
                background: buttonHovered 
                  ? 'linear-gradient(135deg, #0a3d77 0%, #1976d2 100%)'
                  : 'linear-gradient(135deg, #0f52ba 0%, #1e88e5 100%)',
                border: 'none',
                boxShadow: buttonHovered
                  ? '0 6px 16px rgba(15, 82, 186, 0.25)'
                  : '0 4px 12px rgba(15, 82, 186, 0.2)',
                transform: buttonHovered ? 'translateY(-1px)' : 'translateY(0)',
                transition: 'all 0.3s ease'
              }}
              onMouseEnter={() => setButtonHovered(true)}
              onMouseLeave={() => setButtonHovered(false)}
              onMouseDown={() => buttonHovered && setButtonHovered(false)}
              onMouseUp={() => !buttonHovered && setButtonHovered(true)}
            >
              登录系统
            </Button>
            
            {/* 忘记密码链接 */}
            <Button
              type="link"
              style={{ 
                width: '100%',
                marginTop: 16,
                color: linkHovered ? '#0f52ba' : '#4299e1',
                textDecoration: linkHovered ? 'underline' : 'none',
                transition: 'all 0.3s ease'
              }}
              onClick={() => alert('请联系管理员重置密码')}
              onMouseEnter={() => setLinkHovered(true)}
              onMouseLeave={() => setLinkHovered(false)}
            >
              忘记密码?
            </Button>
          </Form.Item>
        </Form>

        {/* 底部版权信息 */}
        <div style={{
          textAlign: 'center',
          marginTop: 40,
          paddingTop: 20,
          borderTop: '1px solid #f1f5f9',
        }}>
          <Text style={{ color: '#94a3b8', fontSize: 12 }}>
            © 2025 硅谷医院管理系统 版权所有
          </Text>
        </div>
      </div>
    </div>
  );
};

export default Login;